package com.sanxiang.exception;

import com.sanxiang.common.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@ControllerAdvice(basePackages = "com.sanxiang.controller")
public class GlobalExceptionHandler {

    //统一异常处理@ExceptionHandler,主要用于业务异常
    @ExceptionHandler(CustomException.class)
    @ResponseBody//返回json串
    public CommonResult customer(HttpServletRequest request, CustomException e) {
        log.error("业务异常信息：" + e);
        return CommonResult.failed(e.getCode(), e.getMsg());
    }

    //统一异常处理@ExceptionHandler,主要用于系统异常
    @ExceptionHandler(Exception.class)
    @ResponseBody//返回json串
    public CommonResult error(HttpServletRequest request, Exception e) {
        log.error("异常信息：" + e);
        return CommonResult.failed(-1, "系统异常");
    }

    //统一异常处理@ExceptionHandler,主要用于空指针异常
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public CommonResult exceptionHandler(HttpServletRequest req, NullPointerException e) {
        log.error("发生空指针异常！原因是:" + e);
        return CommonResult.failed(-1, "空指针异常");
    }


}
